<template>
  <div class="problem-management">
    <div class="toolbar">
      <div class="search-group">
        <div class="search-input">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="search-icon">
            <circle cx="11" cy="11" r="8"></circle>
            <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
          </svg>
          <input 
            type="text" 
            v-model="searchQuery" 
            placeholder="搜索题目..." 
            @keyup.enter="handleSearch"
          >
        </div>
        <button class="btn-search" @click="handleSearch">搜索</button>
      </div>
      <button class="btn-primary" @click="handleAddProblem">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="btn-icon">
          <line x1="12" y1="5" x2="12" y2="19"></line>
          <line x1="5" y1="12" x2="19" y2="12"></line>
        </svg>
        新增题目
      </button>
    </div>

    <div class="problem-table">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>标题</th>
            <th>难度</th>
            <th>提交次数</th>
            <th>通过率</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading" class="loading-row">
            <td colspan="6">
              <div class="loading-spinner"></div>
              加载中...
            </td>
          </tr>
          <tr v-else-if="problems.length === 0" class="empty-row">
            <td colspan="6">
              <div class="empty-state">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="empty-icon">
                  <path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path>
                  <path d="M13 2v7h7"></path>
                </svg>
                暂无题目数据
              </div>
            </td>
          </tr>
          <tr v-else v-for="problem in problems" :key="problem.id">
            <td>{{ problem.id }}</td>
            <td>{{ problem.title }}</td>
            <td>
              <span :class="['difficulty-tag', problem.difficulty]">
                {{ getDifficultyLabel(problem.difficulty) }}
              </span>
            </td>
            <td>{{ problem.submissions || 0 }}</td>
            <td>{{ formatPassRate(problem.passRate) }}</td>
            <td>
              <div class="action-buttons">
                <button class="btn-icon-only" title="编辑" @click="handleEdit(problem)">
                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
                    <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
                  </svg>
                </button>
                <button class="btn-icon-only delete" title="删除" @click="handleDelete(problem)">
                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M3 6h18"></path>
                    <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
                  </svg>
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="pagination">
      <span class="total">共 {{ total }} 条</span>
      <div class="pagination-controls">
        <button 
          class="btn-page" 
          :disabled="currentPage === 1"
          @click="handlePageChange(currentPage - 1)"
        >
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M15 18l-6-6 6-6"></path>
          </svg>
        </button>
        <span class="page-info">第 {{ currentPage }} 页</span>
        <button 
          class="btn-page"
          :disabled="currentPage === totalPages"
          @click="handlePageChange(currentPage + 1)"
        >
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M9 18l6-6-6-6"></path>
          </svg>
        </button>
      </div>
      <div class="page-size">
        <select v-model="pageSize" @change="handlePageSizeChange">
          <option value="10">10 条/页</option>
          <option value="20">20 条/页</option>
          <option value="50">50 条/页</option>
        </select>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import problemApi from '@/api/problem'
import '@/styles/admin/problem.css'
import type { Problem } from '@/api/problem'

interface ProblemData extends Problem {
  difficulty: 'easy' | 'medium' | 'hard';
  submissions?: number;
  passRate?: number;
}

const searchQuery = ref('')
const loading = ref(false)
const problems = ref<ProblemData[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

const getDifficultyLabel = (difficulty: string) => {
  const labels = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return labels[difficulty as keyof typeof labels] || difficulty
}

const formatPassRate = (rate: number) => {
  return rate ? `${(rate * 100).toFixed(1)}%` : '0%'
}

const fetchProblems = async () => {
  loading.value = true
  try {
    const data = await problemApi.getList({
      page: currentPage.value,
      page_size: pageSize.value,
      search: searchQuery.value,
      ordering: '-create_time'
    })
    
    // Transform data to match our interface
    problems.value = data.map(problem => ({
      ...problem,
      difficulty: problem.difficulty.toLowerCase() as 'easy' | 'medium' | 'hard',
      passRate: problem.pass_rate / 100
    }))

    const count = await problemApi.getCount({
      search: searchQuery.value
    })
    total.value = count
  } catch (error) {
    ElMessage.error('获取题目列表失败')
    console.error('Failed to fetch problems:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchProblems()
}

const handleAddProblem = () => {
  // TODO: Implement problem creation dialog
  ElMessage.info('新增题目功能开发中')
}

const handleEdit = (problem: ProblemData) => {
  // TODO: Implement problem editing dialog
  ElMessage.info('编辑题目功能开发中')
}

const handleDelete = async (problem: ProblemData) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除题目 "${problem.title}" 吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // TODO: Implement delete API call
    ElMessage.success('删除成功')
    fetchProblems()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('Failed to delete problem:', error)
    }
  }
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchProblems()
}

const handlePageSizeChange = () => {
  currentPage.value = 1
  fetchProblems()
}

onMounted(() => {
  fetchProblems()
})
</script>
